import { _goodsDetail, _goodsRelated, _cartCount, _addOrDelCollect, _addCart, _footprintNew } from "../../../service/api";
import formatDate from "../../../utils/format";

Page({
  data: {
    id: null, // 商品ID
    goods: {}, // 商品信息
    gallery: [], // 轮播图片
    attribute: [], // 商品参数
    issueList: [], // 常见问题
    comment: [], // 评论
    brand: {}, // 品牌制造商
    specificationList: [], // 规格列表
    productList: [], // 商品数量
    userHasCollect: 0, // 是否收藏
    openAttr: false, // 显示隐藏属性盒子
    amount: 1, // 购买的商品数量
    checkedSpecText: "请选择规格数量", // 选中的规格
    cartCount: 0, // 购物车数量
    spcesPrice: 0, // 规格价格
  },
  onLoad(options) {
    this.setData({ id: options.id });
    this.initData();
  },
  // 初始化
  async initData() {
    wx.showLoading({ title: "加载中..." });
    const detail = await _goodsDetail(this.data.id);
    detail.detail.goods_desc = detail.detail.goods_desc.replace(/\<img/gi, '<img class="rich-image" ');
    const date = new Date(detail.comment.data.add_time * 1000);
    detail.comment.data.add_time = formatDate(date, "yyyy-MM-dd");
    this.setData({
      goods: detail.detail,
      gallery: detail.gallery,
      attribute: detail.attribute,
      issueList: detail.issue,
      comment: detail.comment,
      brand: detail.brand,
      specificationList: detail.specificationList,
      productList: detail.productList,
      userHasCollect: detail.userHasCollect,
    });
    wx.hideLoading();
    _footprintNew(this.data.id);
    this.getCartCount();
    this.getGoodsRelated();
  },
  // 获取推荐
  async getGoodsRelated() {
    const res = await _goodsRelated(this.data.id);
    this.setData({ relatedGoods: res });
  },
  // 获取购物车数量
  async getCartCount() {
    const res = await _cartCount();
    this.setData({ cartCount: res.count });
  },
  // 显示属性盒子
  handleSwitchAttrPop() {
    if (this.data.openAttr === false) {
      this.setData({ openAttr: !this.data.openAttr });
    }
  },
  // 关闭属性盒子
  handleCloseAttr() {
    this.setData({ openAttr: false });
  },
  // 选择规格
  handleCheckSkuValue(e) {
    const { nameId, valueId } = e.target.dataset;
    let specs = this.data.specificationList;
    specs.forEach((item) => {
      // 判断点击的规格类型
      if (item.specification_id === nameId) {
        item.valueList.forEach((child) => {
          // 判断点击的规格项
          if (child.id === valueId) {
            child.checked = !child.checked;
          } else {
            child.checked = false;
          }
        });
      }
    });
    this.setData({ specificationList: specs });
    this.changeSpecInfo();
  },
  // 计算商品价格
  changeSpecPrice() {},
  // 重新计算规格
  changeSpecInfo() {
    const checkSpecs = this.getCheckedSpecsInfo();
    const checkValue = checkSpecs.filter((item) => item.valueId !== 0).map((item) => item.valueText);
    if (checkValue.length > 0) {
      this.setData({ checkedSpecText: checkValue.join(" ") });
    } else {
      this.setData({ checkedSpecText: "请选择规格数量" });
    }
  },
  // 获取选中的规格信息
  getCheckedSpecsInfo() {
    const checkSpecs = [];
    const specs = this.data.specificationList;
    specs.forEach((item) => {
      let obj = {
        nameId: item.specification_id,
        valueId: 0,
        valueText: "",
      };
      item.valueList.forEach((child) => {
        if (child.checked) {
          obj.valueId = child.id;
          obj.valueText = child.value;
        }
      });
      checkSpecs.push(obj);
    });
    return checkSpecs;
  },
  // 判断用户选择的规格是否完整
  isCheckedAllSpces() {
    return this.getCheckedSpecsInfo().some((item) => item.valueId === 0);
  },
  // 判断商品库存
  productStock() {
    let specskey = this.getCheckedSpecsInfo()
      .map((item) => item.valueId)
      .join("_");
    return this.data.productList.filter((item) => item.goods_specification_ids === specskey);
  },
  // 添加收藏
  async handleAddCollect() {
    const result = await _addOrDelCollect({ typeId: 0, valueId: this.data.id });
    if (result.errno === 200) {
      if (result.handleType === "add") {
        wx.showToast({ title: "收藏成功", mask: true });
        this.setData({ userHasCollect: 1 });
      } else {
        this.setData({ userHasCollect: 0 });
      }
    } else {
      wx.showToast({
        title: result.msg,
        icon: "error",
        duration: 1000,
        mask: true,
      });
    }
  },
  // 添加购物车
  handleAddCart() {
    let { openAttr, amount, goods } = this.data;
    if (openAttr === false) {
      this.setData({ openAttr: !openAttr });
    } else {
      if (this.isCheckedAllSpces()) {
        return wx.showToast({ title: "请选择规格", icon: "error", mask: true });
      }
      const checkedProduct = this.productStock();
      if (checkedProduct.length <= 0) {
        return wx.showToast({ title: "库存不足", icon: "error", mask: true });
      } else if (checkedProduct[0].goods_number < amount) {
        return wx.showToast({ title: "商品数量不足", icon: "error", mask: true });
      }

      _addCart({ goodsId: goods.id, number: amount, productId: checkedProduct[0].id }).then((res) => {
        console.log(res);
        if (res.errno === 200) {
          wx.showToast({ title: "添加成功" });
          this.setData({ openAttr: !openAttr, cartCount: res.data.cartTotal.count });
        } else if (res.errno === 400) {
          wx.showToast({ title: res.msg, icon: "error", mask: true });
        }
      });
    }
  },
  // 跳转购物车页面
  handleSkipCartPage() {
    wx.switchTab({ url: "/pages/cart/cart" });
  },
  // 减少
  handleCutNumber() {
    this.setData({ amount: this.data.amount - 1 });
  },
  // 添加
  handleAddNumber() {
    this.setData({ amount: this.data.amount + 1 });
  },
});
